package com.pb.b2b.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pb.b2b.common.exception.CustomException;
import com.pb.b2b.common.service.impl.BaseServiceImpl;
import com.pb.b2b.dao.LanguageDAO;
import com.pb.b2b.model.CategoryLanguage;
import com.pb.b2b.model.Language;
import com.pb.b2b.model.enums.Status;
import com.pb.b2b.service.LanguageService;

@Service
public class LanguageServiceImpl extends BaseServiceImpl implements LanguageService {

	@Autowired
	private LanguageDAO languageDAO;

	@Transactional
	public void createLanguage(Language language) {
		try {
			List<Language> list = findAll(Language.class);
			if (list == null || list.size() == 0) {
				language.setActive("X");
			}
			language.setStatus(Status.AKTIVE);
			language.setDateAdded(new Date());
			language.setDateModified(new Date());

			Language defaultLanguage = getDefaultLanguage();
			List<CategoryLanguage> newCategoryLanguages = new ArrayList<CategoryLanguage>();
			for (CategoryLanguage categoryLanguage : defaultLanguage.getCategoryLanguages()) {
				CategoryLanguage temp = new CategoryLanguage();
				temp.setCategory(categoryLanguage.getCategory());
				temp.setDescription(categoryLanguage.getDescription());
				temp.setKeywords(categoryLanguage.getKeywords());
				temp.setLanguage(language);
				temp.setName(categoryLanguage.getName());
				newCategoryLanguages.add(temp);
			}

			language.setCategoryLanguages(new HashSet<CategoryLanguage>(newCategoryLanguages));

			save(language);
		} catch (Exception e) {
			new CustomException(e, LanguageServiceImpl.class);
		}
	}

	@Transactional
	public void setDefaultLanguage(Language language) {
		try {
			List<Language> languageList = findAll(Language.class);
			for (Language lang : languageList) {
				if (!lang.getId().equals(language.getId())) {
					lang.setActive(null);
				} else {
					lang.setActive("X");
				}
				saveOrUpdate(lang);
			}
		} catch (Exception e) {
			new CustomException(e, LanguageServiceImpl.class);
		}
	}

	@Transactional
	public Language getDefaultLanguage() {
		Language language = null;
		try {
			language = languageDAO.getDefaultLanguage();

		} catch (Exception e) {
			new CustomException(e, LanguageServiceImpl.class);
		}
		return language;
	}

	@Transactional
	public List<Language> getLanguages(Status status) {
		List<Language> languageList = null;
		try {
			languageList = languageDAO.getLanguages(status);
		} catch (Exception e) {
			new CustomException(e, LanguageServiceImpl.class);
		}
		return languageList;
	}
}
